import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;

public class Turret implements Paintable{
	private int x;
	private int y;
	private int vx;
	private int vy;
	private boolean isAutomated = false;
	private int fireRate=10;
	private int lastFire=0;
	private boolean isFireing=false;
	private int barrelLength=20;
	private double theta;
	private Environment e;

	/**
	 * @param x x parameter of the turrets location
	 * @param y y parameter of the turrets location
	 * @param e Environment
	 */
	public Turret(int x, int y, Environment e){
		this.x=x;
		this.y=y;
		this.e=e;
	}

	/**
	 * @param mx x position of mouse
	 * @param my y position of mouse
	 * @return angle from turret to mouse
	 */
	public double angleToMouse(int mx,int my){
		int x=this.x-mx;
		int y=this.y-my;
		double angle = (-1*Math.atan2(y,x))-Math.PI/2;
		this.theta=angle;
		int vx=(int)(this.barrelLength*Math.sin(angle));
		int vy=(int)(this.barrelLength*Math.cos(angle));
		this.vx=vx;
		this.vy=vy;
		return angle;
	}
	
	public void act(int mx, int my){
		angleToMouse(mx,my);
		if(isFireing && lastFire%fireRate==0){
			pFire();
			lastFire=1;
		}
		if(isFireing){
			lastFire++;
		}
		if(!isFireing && lastFire>fireRate){
			lastFire=0;
		}
		if(!isFireing && lastFire!=0){
			lastFire++;
		}
		
	}
	
	/**
	 * Creates a bullet to be fired from this turret
	 */
	public void pFire(){
		e.getbList().add(new Bullet(this.x+this.vx,this.y+this.vy, this.theta, this.e));
	}
	
	/**
	 * @param g
	 */
	public void Paint(Graphics2D g){
		g.setColor(new Color(0,0,255));
		g.fillOval(this.x-10, this.y-10, 20, 20);
		g.setStroke(new BasicStroke(10));
		g.drawLine(this.x,this.y,this.x+this.vx,this.y+this.vy);
		g.setStroke(new BasicStroke(1));
	}

	/**
	 * @return the x
	 */
	public int getX() {
		return x;
	}

	/**
	 * @param x the x to set
	 */
	public void setX(int x) {
		this.x = x;
	}

	/**
	 * @return the y
	 */
	public int getY() {
		return y;
	}

	/**
	 * @param y the y to set
	 */
	public void setY(int y) {
		this.y = y;
	}

	/**
	 * @return the theta
	 */
	public double getTheta() {
		return theta;
	}

	/**
	 * @param theta the theta to set
	 */
	public void setTheta(double theta) {
		this.theta = theta;
	}

	/**
	 * @return the isFireing
	 */
	public boolean isFireing() {
		return isFireing;
	}

	/**
	 * @param isFireing the isFireing to set
	 */
	public void setFireing(boolean isFireing) {
		this.isFireing = isFireing;
	}
}
